<template>
    <span class="left-align"><h4>指派网格员</h4></span>
    <el-form :model="location" label-width="auto" style="max-width: 100vw">
		
      <el-form-item>
        <el-row :gutter="20" class="el-row-align-center" style="width: 100%; background-color: lightblue;">
        <el-col :span="3">
            <span><h4>是否异地指派：</h4> </span>
            <el-switch v-model="location.ifRemote" @change="handleIfRemoteChange"></el-switch>
          </el-col>

          <el-col :span="3">
            <span><h4>省区域：</h4></span>
				<el-select
				  v-model="location.provinceValue"
				  placeholder="--全部--"
				  style="width: 100px"
				  @change="handleProvinceChange"
				  :disabled="!location.ifRemote"
				  size="default"
				>
				  <el-option				
					v-for="item in provinces"
					:key="item.id"
					:label="item.province"
					:value="item.id"
				  />
				</el-select>
          </el-col>

          <el-col :span="3">
            <span><h4>市区域：</h4></span>
				<el-select
				  v-model="location.cityValue"
				  placeholder="--全部--"
				  style="width: 100px"
				  :disabled="!location.provinceValue"
				  size="default"
				>
				  <el-option
					v-for="item in citys"
					:key="item.id"
					:label="item.areaName"
					:value="item.id"
				  />
				</el-select>
          </el-col>

          <el-col :span="4">
            <span><h4>异地指派给：</h4></span>
            <el-select
              placeholder="--全部--"
			  v-model="location.grider"
              size="default"
              style="width: 100px"
            >
              <el-option
                v-for="item in griders"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-col>

          <el-col :span="2">
            <el-button type="primary" @click.prevent="designate()">异地指派</el-button>
          </el-col>
        </el-row>
      </el-form-item>

	  	<el-form-item>
	  	  <el-row :gutter="100"  style="width: 100%;">
	  			<el-col :span="16">
	  			  <el-table :data="tableData"  :show-header="false" border style="flex; width: 100%">
	  				<el-table-column prop="attribute" label="属性" ></el-table-column>
	  				<el-table-column label="属性">
	  					<template #default="scope">
	  					  <el-tag class="eltag"
	  						v-for="(tag, index) in scope.row.tags"
	  						:key="index"
	  						:type="tag.type"
	  					  >
	  						{{ tag.text }}
	  					  </el-tag>
	  					</template>
	  				</el-table-column>
	  			  </el-table>
	  			</el-col>
	  			
	  			<el-button @click="handleReturn" type="primary" plain>返回</el-button>
	  		</el-row>	
	  	</el-form-item>
	  
    </el-form>
</template>

<script setup>
import { computed, ref, reactive,onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router';
import axios from '@/axios';
import { ElMessage, ElMessageBox } from 'element-plus';
const router=useRouter()
const route=useRoute()
const routequery=route.query
const tokenValue=localStorage.getItem('token')


const tableData = ref([
  { tags: [{ type: 'primary', text: routequery.id }],
	attribute: '公众监督反馈信息编号'},
  { tags: [{ type: 'primary', text: routequery.svName },
		   { type: 'primary', text:	routequery.svGender },
		   { type: 'primary', text: routequery.svBirthday }],
	attribute: '反馈者信息'},
  { tags: [{ type: 'primary', text:	routequery.svPhone  }],
	attribute: '反馈者联系电话'},
  { tags: [{ type: 'primary', text:	routequery.province  },
		   { type: 'primary', text: routequery.city },
		   { type: 'primary', text: routequery.address }],
	attribute: '反馈信息所在地址'},
  { tags: [{ type: 'primary', text:	routequery.content  }],
	attribute: '反馈信息描述'},
  { tags: [{ type: 'primary', text:	routequery.aqi  },
		   { type: 'primary', text: routequery.aqiChinese }],
	attribute: '预估等级'},
  { tags: [{ type: 'primary', text:	routequery.date },
		   { type: 'primary', text:	routequery.time }],
	attribute: '反馈日期时间'},		   
]);
const location=ref({
	provinceValue:'',
	cityValue:'',
	grider:'',
	ifRemote:false
})

const handleReturn=()=>{
	router.push('/admin/svDataManage/svDataList')
}


const provinces = ref([])
const citys=ref([])
const fetchProvinces=async ()=>{
		try{
			axios.get('/service-admin/province/getAllProvince',
			{
				headers: {
				  'Authorization': `Bearer ${tokenValue}` // 在请求头中添加 Bearer Token
				},
			})
			  .then(response => {
				provinces.value=response.data.sendResult
				
			  })
			  .catch(error => {
				console.error('Error:', error);
			  });
		}catch(err){
			console.error('Error fetching data:',err.message)
		}

}

// 监听 location.value.provinceValue 的变化，计算出对应城市列表
watch(() => location.value.provinceValue, async (newVal, oldVal) => {
  if (location.value.provinceValue && location.value.ifRemote) {
	const provinceid = location.value.provinceValue;
	try {
	  const response = await axios.get('/service-admin/city/getByProvince', {
		params: {
		  provinceId: provinceid
		},
		headers: {
		  'Authorization': `Bearer ${tokenValue}` // 在请求头中添加 Bearer Token
		}
	  });
	  if(response.data.code==0)
	  {
		citys.value = response.data.sendResult;
	  }
	  else{
		  citys.value=''
		  ElMessage.warning(response.data.sendResult)
	  }
	  
	} catch (error) {
	  console.error('Error fetching cities:', error);
	}
  } else {
	console.error(`Province not found`);
  }
});

const handleProvinceChange = () => {
  location.value.cityValue = ''
}
const handleIfRemoteChange=()=>{
	location.value.provinceValue=''
	location.value.cityValue=''
	location.value.grider=''
}

const griders=ref([])
const fetchGriders=async ()=>{
	console.log(!location.value.ifRemote)
	console.log(routequery)
	if(!location.value.ifRemote)
	{
	try{
		axios.get('/service-admin/staff/getGridByLocation',
		{
			headers:{
				'Authorization': `Bearer ${tokenValue}` // 在请求头中添加 Bearer Token
			},
			params:{
				provinceId:routequery.provinceId,
				cityId:routequery.cityId
			}
		})
		.then(response =>{
			if(response.data.code==0)
			{
				griders.value=response.data.sendResult
			}
			else{
				griders.value=''
				ElMessage.warning(response.data.sendResult)
				ElMessageBox.confirm(
				'当前地区没有网格员，是否异地指派网格员？',
				'提示',
				{
					distinguishCancelAndClose:true,
					confirmButtonText:'是',
					cancelButtonText:'否'
				}
				)
				.then(()=>{
					location.value.ifRemote=true
					ElMessage.success('操作成功')
				})
				.catch((action)=>{
					if(action=='cancel')
					ElMessage.warning("当前地区没有网格员，请联系管理员或开启异地指派")
				})
			}
		})
		.catch(error =>{
			console.error('Error:',error);
		})
	}catch(err){
		console.error('Error fetching data:',err.message)
	}
}
}



watch(()=>location.value.cityValue, async(newVal,oldVal)=>{
	if(location.value.cityValue && location.value.ifRemote){
		try{
			const response=await axios.get('/service-admin/staff/getGridByLocation',
		{
			headers:{
				'Authorization': `Bearer ${tokenValue}` // 在请求头中添加 Bearer Token
			},
			params:{
				provinceId:location.value.provinceValue,
				cityId:location.value.cityValue
			}
		})
			if(response.data.code==0)
			{
				griders.value=response.data.sendResult
			}
			else{
				griders.value=''
				ElMessage.warning(response.data.sendResult)
			}
		}catch(e){
			console.error('Error fetching data:',err.message)
		}
	}
})



const designate = async () => {
  try {
    const { grider, cityValue, provinceValue } = location.value;
    const { feedbackId } = routequery;
	console.log(cityValue," ",feedbackId)
    const response = await axios.post(
      '/service-admin/verification/addVerification',
      {
        gsId: grider,
        cityId: cityValue,
        provinceId: provinceValue,
        feedbackId: feedbackId,
      },
      {
        headers: {
          'Authorization': `Bearer ${tokenValue}`,
        },
      }
    );

    if (response.data.code === 0) {
      ElMessage.success('指派成功!');
    } else {
      ElMessage.warning(response.data.message || '操作失败');
    }
  } catch (error) {
    ElMessage.error('请求失败');
    console.error('Error:', error);
  }
};



onMounted(()=>{
	fetchProvinces()
	fetchGriders()
	
})
</script>

<style>
	
.eltag{
	margin-left: 10px;
}

.left-align {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.el-col-align-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.el-row-align-center {
  display: flex;
  align-items: center;
}

.el-row-align-center > .el-col {
  display: flex;
  align-items: center;
}
</style>